<template>
    <section>
        <!--工具条-->
        <div class="section-content clearfix">
            <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
                <el-form :inline="true" :model="filters" @submit.native.prevent>
                    <el-form-item style="float: left;">
                        <el-input v-model="filters.name" placeholder="模板名" @keyup.enter.native="getUsers()"></el-input>
                    </el-form-item>
                    <el-form-item class="tool-bt">
                        <el-button :type="buttonColor" v-on:click="getUsers">查询</el-button>
                    </el-form-item>
                    <el-form-item v-if="menubt.indexOf('/device_data_recipe/post') > -1">
                        <el-button :type="buttonColor" @click="handleAdd">新增</el-button>
                    </el-form-item>
                </el-form>
            </el-col>

            <!--列表-->
            <el-table :data="query" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
                :header-row-style="{ backgroundColor: titleColor }" style="width: 100%;">
                <!-- <el-table-column type="selection">
            </el-table-column> -->
                <el-table-column align="center" type="index" label="序号" width="80" :index="indexMethod">
                </el-table-column>
                <el-table-column align="center" prop="name" label="模板名称">
                    <template scope="scope">
                        <span class="pb-name" @click="getrows(scope.$index, scope.row)">{{ scope.row.name }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="size" label="关联数据点数">
                </el-table-column>
                <el-table-column align="center" prop="updateTime" label="更新时间">
                </el-table-column>
                <el-table-column align="center" label="操作">
                    <template scope="scope">
                        <i v-if="menubt.indexOf('/device_data_recipe/put') > -1" @click="handleEdit(scope.$index, scope.row)"
                            title="编辑" icon="el-icon-edit" circle class="pb-icon icon-edit"></i>
                        <i v-if="menubt.indexOf('/device_data_recipe/delete') > -1"
                            @click="handleDel(scope.$index, scope.row)" icon="el-icon-delete" circle title="删除"
                            class="pb-icon icon-delete"></i>
                        <i v-if="custom_version == 0" class="el-icon-download"
                            style="font-size:30px;cursor:pointer;color:#0099cc;" title="模板下载"
                            @click="tableToExcel(scope.$index, scope.row)"></i>
                        <i v-if="custom_version == 2" class="el-icon-download"
                            style="font-size:30px;cursor:pointer;color:#0099cc;" title="模板下载"
                            @click="tableToExcel1(scope.$index, scope.row)"></i>
                        <i class="el-icon-document" style="font-size:30px;cursor:pointer;color:#0099cc;" title="复制数据模板"
                            @click="handCopy(scope.$index, scope.row)"></i>
                    </template>
                </el-table-column>
            </el-table>

            <!--工具条-->
            <el-col :span="24" class="toolbar">
                <!-- <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button> -->
                <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10"
                    :total="total" style="float:right;">
                </el-pagination>
            </el-col>
        </div>
        <!--编辑界面-->
        <el-dialog title="编辑" v-show="editFormVisible" v-model="editFormVisible" :custom-class="dialogTitleColor"
            @close="editFormVisible = false">
            <div slot="footer" style="text-align: left; ">
                <el-form :model="editForm" label-width="100px" :rules="editFormRules" ref="editForm">
                    <el-form-item label="模板名称" prop="name">
                        <el-input v-model="editForm.name" auto-complete="off"></el-input>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align:right;">
                    <el-button @click.native="closeform">取消</el-button>
                    <el-button :type="buttonColor" @click.native="editSubmit" :loading="editLoading">提交</el-button>
                </div>
            </div>
        </el-dialog>

        <!--新增界面-->
        <el-dialog title="新增" v-show="addFormVisible" v-model="addFormVisible" :custom-class="dialogTitleColor"
            @close="addFormVisible = false">
            <div slot="footer" style="text-align: left; ">
                <el-form :model="addForm" label-width="100px" :rules="addFormRules" ref="addForm">
                    <el-form-item label="模板名称" prop="name">
                        <el-input v-model="addForm.name" auto-complete="off"></el-input>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align: right;">
                    <el-button @click.native="closeform">取消</el-button>
                    <el-button :type="buttonColor" @click.native="addSubmit" :loading="addLoading">提交</el-button>
                </div>
            </div>
        </el-dialog>
        <el-dialog title="编辑" v-show="copyVisible" v-model="copyVisible" :custom-class="dialogTitleColor" 
            @close="copyVisible = false">
            <div slot="footer" style="text-align: left; ">
                <el-form :model="copyForm" label-width="120px" :rules="copyFormRules" ref="copyForm">
                    <el-form-item label="请输入新名称" prop="name">
                        <el-input v-model="copyForm.name" auto-complete="off"></el-input>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align:right;">
                    <el-button @click.native="copyVisible = false">取消</el-button>
                    <el-button :type="buttonColor" @click.native="copySubmit" :loading="editLoading">提交</el-button>
                </div>
            </div>
        </el-dialog>
    </section>
</template>

<script>
// import util from './../common/js/util'
//import NProgress from 'nprogress'
import {
    device_data_recipe_query,
    device_data_recipe_put,
    alarms_post_user,
    alarms_delete_user,
    alarms_put_user,
    device_data_recipe_delete,
    device_data_recipe_post,
    device_data_recipe_list_body,
    unit_query,
    device_data_recipe_copy
} from '../../api/api';

export default {
    data() {
        return {
            filters: {//查询
                name: ''
            },
            query: [],//列表数据
            total: 0,
            page: 1,
            listLoading: false,
            sels: [], //列表选中列

            editFormVisible: false, //编辑界面是否显示
            editLoading: false,
            editFormRules: {//非空验证
                name: [{
                    required: true,
                    message: '请输入模板名',
                    trigger: 'blur'
                }, { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }]
            },
            //编辑界面数据
            editForm: {
                id: '',
                name: '',

            },

            addFormVisible: false, //新增界面是否显示
            addLoading: false,
            copyVisible: false,
            addFormRules: {
                name: [{
                    required: true,
                    message: '请输入模板名',
                    trigger: 'blur'
                }, { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }],
                path: [{
                    required: true,
                    message: '请输入path',
                    trigger: 'blur'
                }

                ]
            },
            //新增界面数据
            addForm: {
                name: '',
            },
            copyFormRules: {
                name: [{
                    required: true,
                    message: '请输入模板名',
                    trigger: 'blur'
                }, { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }]
            },
            copyForm: {
                name: '',
                id: '',
            },
            unitlist: '',
            custom_version: this.CustomVersion()
        }
    },
    computed: {//主题色
        buttonColor() {
            return this.$store.state.buttonColor
        },
        titleColor() {
            return this.$store.state.titleColor
        },
        dialogTitleColor() {
            return this.$store.state.dialogTitleColor
        },
    },
    created: function () {
        var _this = this;
        document.onkeydown = function (e) {//键盘回车
            let key = window.event.keyCode;
            console.log(window.event);
            if (!_this.addFormVisible) {
            } else {

                if (key == 13) {
                    _this.addSubmit()
                        ;
                }
            }
        };
    },
    methods: {
        indexMethod(index) {
            let num = (this.page - 1) * 10 + index + 1;//为了序列号从1开始
            return num;
        },
        //性别显示转换
        formatSex: function (row, column) {//模版名称跳页面
            return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
        },
        // 模版内容跳转
        getrows: function (index, row) {
            // this.$store.dispatch("setCityName", row);
            console.log(this,666);
            if (this.menubt.indexOf('/device_data_recipe/get') == -1) {
                this.$message({
                    message: '您没有获取数据模板的权限',
                    type: 'warning'
                });
                return false;
            }
            sessionStorage.setItem('deviceDataRecipeId', row.id)
            this.$router.push("/template/edit");
        },
        handleCurrentChange(val) {
            this.page = val;
            this.getUsers();
        },
        //渲染获取菜单列表
        getUsers() {
            if (this.menubt.indexOf('/device_data_recipe/query') == -1) {
                this.$message({
                    message: '您没有查询数据模板的权限',
                    type: 'warning'
                });
                return false;
            }
            let para = {
                pageNo: this.page,//当前页
                pageSize: 10,//条数
                name: this.filters.name//名称
            };
            this.listLoading = true;
            //NProgress.start();
            device_data_recipe_query(para).then((res) => {
                this.begCode(res.code);
                this.total = res.data.totalCount;
                this.query = res.data.list;
                this.listLoading = false;
                //NProgress.done();
            });
        },
        //删除
        handleDel: function (index, row) {
            this.$confirm('确认删除该模板吗?', '提示', {
                type: 'warning'
            }).then(() => {
                this.listLoading = true;
                //NProgress.start();
                let para = {
                    idList: [row.id]
                };
                device_data_recipe_delete(para).then((res) => {
                    this.begCode(res.code, res.message);
                    this.listLoading = false;
                    if (res.code == 0) {

                        //NProgress.done();
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getUsers();

                    }
                });
            }).catch(() => {

            });
        },
        //显示编辑界面弹窗
        handleEdit: function (index, row) {
            this.editFormVisible = true;
            this.editForm = Object.assign({}, row);
        },
        //复制数据配方的改名页面
        handCopy: function (index, row) {
            console.log(row)
            this.copyVisible = true
            this.copyForm.id = row.id
        },
        //显示新增界面弹窗
        handleAdd: function () {
            this.addFormVisible = true;
            this.addForm = {
                name: '',
            };
        },
        //编辑
        editSubmit: function () {
            this.$refs.editForm.validate((valid) => {
                if (valid) {
                    this.$confirm('确认提交吗？', '提示', {}).then(() => {
                        this.editLoading = true;
                        let para = Object.assign({}, this.editForm);

                        device_data_recipe_put(para).then((res) => {
                            this.begCode(res.code);

                            if (res.code == 0) {
                                this.editLoading = false;
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs.editForm.resetFields();
                                this.editFormVisible = false;
                                this.getUsers();
                            }
                        });
                    });
                }
            });
        },
        closeform(){
            this.editFormVisible=false
            this.$refs.editForm.resetFields();
            this.addFormVisible=false
            this.$refs.addForm.resetFields();

        },
        //复制数据配方
        copySubmit() {
            this.$refs.copyForm.validate((valid) => {
                if (valid) {
                    this.$confirm('确认提交吗？', '提示', {}).then(() => {
                        this.editLoading = true;
                        let para = {
                            id: this.copyForm.id,
                            name: this.copyForm.name
                        }
                        device_data_recipe_copy(para).then((res) => {
                            if (res.code == 0) {
                                this.editLoading = false;
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.copyVisible = false
                                this.$refs['copyForm'].resetFields();
                                this.getUsers();
                            }
                        })
                    })
                }
            })
        },
        //新增
        addSubmit: function () {
            this.$refs.addForm.validate((valid) => {

                if (valid) {
                    this.$confirm('确认提交吗？', '提示', {}).then(() => {

                        this.addLoading = true;
                        //NProgress.start();
                        let para = Object.assign({}, this.addForm);

                        device_data_recipe_post(para).then((res) => {
                            this.begCode(res.code);
                            this.addLoading = false;
                            if (res.code == 0) {
                                //NProgress.done();
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.getUsers();
                                sessionStorage.setItem('deviceDataRecipeId', res.data)
                                this.$router.push("/template/edit");
                                this.addFormVisible = false;
                                this.addLoading = false;

                            }

                        });
                    });
                }
            })
        },
        selsChange: function (sels) {
            this.sels = sels;
        },
        //批量删除
        batchRemove: function () {
            var ids = this.sels.map(item => item.id).toString();
            this.$confirm('确认删除选中记录吗？', '提示', {
                type: 'warning'
            }).then(() => {
                this.listLoading = true;
                //NProgress.start();
                let para = {
                    idList: ids.split(',')
                };
                device_data_recipe_delete(para).then((res) => {
                    this.begCode(res.code);
                    this.listLoading = false;
                    //NProgress.done();
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                    this.getUsers();
                });
            }).catch(() => {

            });
        },
        tableToExcel1(index, row) {//电量定制custom_version=2
            var jsonData = [];

            let para = {
                deviceDataRecipeId: row.id,
            }
            device_data_recipe_list_body(para).then((res) => {
                console.log(res)
                for (let i in res.data.list) {
                    var register //数据点地址
                    var serial //串口
                    var registertype //数据点类型
                    if (res.data.list[i].register.indexOf('-') > -1 && res.data.list[i].register.indexOf('#') > -1) {
                        register = res.data.list[i].register.split('-')[0]
                        serial = res.data.list[i].register.split('-')[1].split('#')[0]
                        registertype = res.data.list[i].register.split('#')[1]
                    } else if (res.data.list[i].register.indexOf('-') == -1 && res.data.list[i].register.indexOf('#') > -1) {
                        register = res.data.list[i].register.split('#')[0]
                        serial = ""
                        registertype = res.data.list[i].register.split('#')[1]
                    } else {
                        register = res.data.list[i].register
                        serial = ""
                        registertype = ""
                    }
                    jsonData[i] = {
                        name: res.data.list[i].name,//数据点名字
                        register: register,//数据点地址
                        dataType: res.data.list[i].dataType,//数据类型
                        valueKindText: res.data.list[i].valueKindText,//数值类型
                        decimalAccuracy: res.data.list[i].decimalAccuracy,//小数点位数
                        serial: serial, //串口
                        registertype: registertype,//数据点类型
                        unit: res.data.list[i].unit,//单位
                        writeRead: res.data.list[i].writeReadText,//读写属性
                        dataRestrict: res.data.list[i].dataRestrict,//数据点限制
                        ifVisible: res.data.list[i].ifVisible, //是否展示
                        remark: res.data.list[i].remark, //备注
                        deviceRecipePictureGroupId: res.data.list[i].deviceRecipePictureGroupId, //图标组        
                    };

                    if (jsonData[i].dataType == 0) {
                        jsonData[i].dataType = "数值型"
                    } else if (jsonData[i].dataType == 1) {
                        jsonData[i].dataType = "开关型"
                    }
                    else {
                        jsonData[i].dataType = "字符型"
                    };
                    if (jsonData[i].dataRestrict == 0) {
                        jsonData[i].dataRestrict = "公开"
                    } else if (jsonData[i].dataRestrict == 11) {
                        jsonData[i].dataRestrict = "不公开"
                    } else {
                        jsonData[i].dataRestrict += "级"
                    }

                    if (jsonData[i].ifVisible == "0") {
                        jsonData[i].ifVisible = "不展示"
                    } else {
                        jsonData[i].ifVisible = "展示"
                    }
                    if (jsonData[i].registertype == 0) {
                        jsonData[i].registertype = "保持数据点"
                    } else {
                        jsonData[i].registertype = "线圈"
                    }

                }
                console.log(jsonData)

                //列标题，逗号隔开，每一个逗号就是隔开一个单元格
                // let str = `数据点名称,数据点地址,数据类型,数值类型,整数位数,小数位数,单位,读写,权限,是否展示,描述,图标组\n`;
                let str = `数据点名称,数据点地址,数据类型,数值类型,小数位数,串口号,数据点类型,单位,读写,权限,是否展示,描述,图标组\n`;
                //增加\t为了不让表格显示科学计数法或者其他格式
                for (let i = 0; i < jsonData.length; i++) {
                    for (let item in jsonData[i]) {
                        str += `${jsonData[i][item]},`;
                    }
                    str += '\n';
                }
                //encodeURIComponent解决中文乱码
                let uri = 'data:text/xls;charset=utf-8,\ufeff' + encodeURIComponent(str);
                //通过创建a标签实现
                let link = document.createElement("a");
                link.href = uri;
                //对下载的文件命名
                link.download = row.name + ".xls";
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            })

        },
        tableToExcel(index, row) {
            var jsonData = [];

            let para = {
                deviceDataRecipeId: row.id,
            }
            device_data_recipe_list_body(para).then((res) => {
                console.log(res)
                for (let i in res.data.list) {

                    jsonData[i] = {
                        name: res.data.list[i].name,//数据点名字
                        register: res.data.list[i].register,//数据点地址
                        dataType: res.data.list[i].dataType,//数据类型
                        valueKindText: res.data.list[i].valueKindText,//数值类型
                        // integerAccuracy: res.data.list[i].integerAccuracy,//整数位数
                        decimalAccuracy: res.data.list[i].decimalAccuracy,//小数点位数
                        unit: res.data.list[i].unit,//单位
                        // formula:res.data.list[i].formula,//显示公式
                        writeRead: res.data.list[i].writeReadText,//读写属性
                        dataRestrict: res.data.list[i].dataRestrict,//数据点限制
                        ifVisible: res.data.list[i].ifVisible, //是否展示
                        remark: res.data.list[i].remark, //备注
                        deviceRecipePictureGroupId: res.data.list[i].deviceRecipePictureGroupId, //图标组        
                    };


                    if (jsonData[i].dataType == 0) {
                        jsonData[i].dataType = "数值型"
                    } else if (jsonData[i].dataType == 1) {
                        jsonData[i].dataType = "开关型"
                    }
                    else {
                        jsonData[i].dataType = "字符型"
                    };
                    if (jsonData[i].dataRestrict == 0) {
                        jsonData[i].dataRestrict = "公开"
                    } else if (jsonData[i].dataRestrict == 11) {
                        jsonData[i].dataRestrict = "不公开"
                    } else {
                        jsonData[i].dataRestrict += "级"
                    }

                    if (jsonData[i].ifVisible == "0") {
                        jsonData[i].ifVisible = "不展示"
                    } else {
                        jsonData[i].ifVisible = "展示"
                    }

                }
                console.log(jsonData)

                //列标题，逗号隔开，每一个逗号就是隔开一个单元格
                // let str = `数据点名称,数据点地址,数据类型,数值类型,整数位数,小数位数,单位,读写,权限,是否展示,描述,图标组\n`;
                let str = `数据点名称,数据点地址,数据类型,数值类型,小数位数,单位,读写,权限,是否展示,描述,图标组\n`;
                //增加\t为了不让表格显示科学计数法或者其他格式
                for (let i = 0; i < jsonData.length; i++) {
                    for (let item in jsonData[i]) {
                        str += `${jsonData[i][item]},`;
                    }
                    str += '\n';
                }
                //encodeURIComponent解决中文乱码
                let uri = 'data:text/xls;charset=utf-8,\ufeff' + encodeURIComponent(str);
                //通过创建a标签实现
                let link = document.createElement("a");
                link.href = uri;
                //对下载的文件命名
                link.download = row.name + ".xls";
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

                // var str =
                //     '<tr><td>数据点名称</td><td>数据类型</td><td>数值类型</td><td>数据点地址</td><td>小数位数</td><td>单位</td><td>显示公式</td><td>数据点限制</td><td>读写属性</td></tr>'

                //     //Worksheet名
                //     for (let i = 0; i < jsonData.length; i++) {
                //         str += '<tr>';
                //         for (let item in jsonData[i]) {
                //             //增加\t为了不让表格显示科学计数法或者其他格式
                //             str += `<td>${ jsonData[i][item] + '\t'}</td>`;
                //         }
                //         str += '</tr>';
                //     }
                //     var worksheet = 'Sheet1'
                //     var uri = 'data:application/vnd.ms-excel;base64,';
                //     //下载的表格模板数据
                //     var template =
                //     `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">     
                //     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                //     <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
                //     <x:Name>${worksheet}</x:Name>
                //     <x:Name>${worksheet}</x:Name>
                //     <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
                //     </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
                //     </head><body><table>${str}</table></body></html>`;
                //     //下载模板
                //     window.location.href = uri + this.base64(template)

            })

        },
        base64(s) {
            return window.btoa(unescape(encodeURIComponent(s)))
        },

    },
    mounted() {
        this.menubt = localStorage.getItem('menubt');
        this.getUsers();
        let para1 = {
            pageNo: 1,
            pageSize: 999,
        }
        unit_query(para1).then((res) => {
            this.begCode(res.code);
            if (res.code == 0) {
                this.addLoading = false;
                this.unitlist = res.data.list;
            }
        });
    }
}
</script>

<style scoped></style>